<template>
    <div class="msg-cover" v-show="show">
        <div class="msg-alert dialog" v-show="show" ref="dialog" :style="{ 'margin-left': marginLeft + 'px', 'margin-top': marginTop + 'px', 'visibility': visibility ? 'visible' : 'hidden' }">
            <div class="msg-header" @mousedown="dragElement">
                <span class="msg-title" v-html="title"></span>
                <button type="button" class="btn-close msg-close" @click.stop="doHideDialog"></button>
            </div>
            <div class="msg-body" :style="{ 'width': width ? width + 'px' : 'inhert', 'max-width': maxWidth + 'px', 'max-height': height + 'px' }">
                <slot></slot>
            </div>
            <div class="msg-footer">
                <div class="footer-button">
                    <slot name="footer"></slot>
                    <button v-if="save" type="button" class="btn btn-secondary" @click.stop="doSave">确定</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { dragElement } from '../Utils';
import './style.less';
import { ref, watch } from 'vue';

const props = defineProps<{
    modelValue: boolean,
    title: string,
    width?: number,
    height?: number,
    save?: () => boolean
}>();
const emit = defineEmits(['update:modelValue']);
const show = ref(props.modelValue);
const dialog = ref(null);
let maxWidth = ref(400);
let dialogHeight = ref(100);
const marginLeft = ref(0);
const marginTop = ref(0);
const visibility = ref(false);
watch(() => props.modelValue, () => {
    show.value = props.modelValue;
    visibility.value = props.modelValue;
    maxWidth.value = window.innerWidth - 300;
    if (props.height) {
        dialogHeight.value = props.height;
    } else {
        dialogHeight.value = window.innerHeight - 300;
    }
    if (!visibility.value) {
        return;
    }
    visibility.value = false;
    const targetDialog = dialog.value;
    if (!targetDialog) {
        return;
    }
    setTimeout(() => {
        const div = targetDialog as HTMLDivElement;
        const style = window.getComputedStyle(div);
        const dialogWidth = parseInt(style.width);
        const dialogHeight = parseInt(style.height);
        marginLeft.value = -(dialogWidth / 2);
        marginTop.value = -(dialogHeight / 2);
        visibility.value = true;
    }, 0);
});
const doHideDialog = () => {
    show.value = false;
    emit('update:modelValue', false);
}

const doSave = () => {
    if (!props.save) {
        return;
    }
    if (!props.save()) {
        return;
    }
    doHideDialog();
}
</script>

<style lang="less" scoped></style>
